<?php
	
	class dbUtil{

		/*建立连接需要一个四元组,(数据库的主机，用户名，密码，数据库名)*/
		public $servername = "";
		public $username = "";
		public $password = "";
		public $dbname = "";
		public $aMaxTry = array('query'=>1,'connect'=>1);
		public $conn = NULL;
		public $result = false;    //表示查询失败，而不是没有查到结果

		/*1. 设置主机，用户名以及密码函数*/
		function __construct($dbhost, $dbuser, $dbpass, $dbname){
			$this->servername = $dbhost;
			$this->username = $dbuser;
			$this->password = $dbpass;
			$this->dbname = $dbname;
		}

		/*2. 最大尝试次数，连接数据库的最大尝试次数，指定最大查询次数*/
		public function setMaxTry($sType,$iTimes){
			$this->aMaxTry[$sType] = (int)$iTimes;
		}

		/*3. 数据库连接*/
		//返回true或者false，表示是否连接成功
		public function connect(){
			for($i = 0; $i < $this->aMaxTry['connect']; $i++){
				$this->conn = new mysqli($this->servername, $this->username, $this->password, $this->dbname);
				if($this->conn->connect_error == NULL){
					break;
				}
			}
			return $this->conn?true:false;
		}

		/*4. 设置字符编码*/
		public function setCharset($sCharset){
			for($i = 0; $i < $this->aMaxTry['query']; $i++){
				if($this->conn->query('set names '.$sCharset)){
					return true;
				}
			}
			return false;
		}

		/*5. 发起查询与获取查询结果*/
		//返回true或者false，明确表示是否查询成功
		//查询结果放在 $this->result中，可能是true false或者结果集
		public function query($q){
			$this->result = false;   //默认为查询失败
			for($i = 0; $i < $this->aMaxTry['query']; $i++){
				//如果失败，固定返回FALSE,如果成功返回结果集或者TRUE
				$this->result = $this->conn->query($q);
				if($this->result){
					break;
				}
			}
			return $this->result?true:false;
		}
		//获取结果集
		public function getResult(){
			return $this->result;
		}

		public function getConnection(){
			return $this->conn;
		}

		public function close(){
			$this->conn->close();
		}



	}

	

	
?>